<template>
  <div>
    <div class="backFont"><el-button icon="el-icon-arrow-left" @click="back()">返回</el-button></div>
    <el-form
      :model="addForm"
      :rules="rules"
      ref="ruleForm"
      :label-position="'right'"
      label-width="90px"
      class="demo-ruleForm mt20 errorForm"
    >
    <el-form-item label="*时间：" prop="dateTime">
      <el-date-picker
        class="selectInput"
        clearable
        v-model="addForm.dateTime"
        type="daterange"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
      >
      </el-date-picker>
    </el-form-item>
      <!-- 入库类型字典 -->
      <el-form-item label="*地块：" prop="landName">
        <span class="greyColor">{{ addForm.landName }}</span>
        <!-- <el-select class="selectInput" disabled clearable v-model="addForm.landIds" placeholder="请选择地块">
          <el-option
            v-for="item in baseInfoList"
            :key="item.baseId"
            :label="item.baseName"
            :value="item.baseId"
          >
          </el-option>
        </el-select> -->
        <!--<el-input readonly @click.native="getAgriLand()" suffix-icon="el-icon-arrow-right" v-model="addForm.landName" placeholder="请选择地块" />-->
      </el-form-item>
      <el-form-item label="*操作人：" prop="userId">
        <el-select class="selectInput" clearable v-model="addForm.userId" placeholder="请选择">
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.name"
            :value="item.userId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="*农事类型：" prop="agriCode">
        <!-- <el-select class="selectInput" ref="selectInput" @visible-change="visibleChange" v-model="addForm.agriCode" clearable placeholder="请选择">
            <el-option
              v-for="item in farmsList"
              :key="item.userId"
              :label="item.name"
              :value="item.code"
            >
            </el-option>
        </el-select> -->
        <div class="selectInputMax">
          <el-button
            class="typeBtn"
            :class="addForm.agriCode === item.code && 'checkBoxAll'"
            @click="addForm.agriCode = item.code"
            v-for="item in farmsList"
            :key="item.userId"
          >
            {{ item.name }}
          </el-button>
        </div>
      </el-form-item>
      <el-form-item label="备注：" prop="remark">
        <el-input  class="selectInputMax" v-model="addForm.remark" rows="4" type="textarea" placeholder="请输入备注内容">
        </el-input>
      </el-form-item>
      <!-- <el-form-item class="textRight">
        <el-button type="primary" @click="submitForm('ruleForm')"
          >保存</el-button
        >
      </el-form-item> -->
    </el-form>
    <div class="submitBottom">
      <el-button
        size="small"
        class="editBtn editBtnNone"
        @click="back()"
        >取消</el-button
      >
      <el-button
        class="editBtn"
        type="primary"
        size="small"
        @click="submitForm('ruleForm')"
      >
        确定
      </el-button>
    </div>
  </div>
</template>

<script>
import { getUserListApi, getSysSonDictListApi, addDic } from '@/api/dict'
import { getBaseInfolistApi, addAgriplantApi, updateAgriplan, getDetailById } from '@/api/baseInfo'
// import farmStockDialog from './components/farmStockDialog'
export default {
  name: 'DateTimeAdd',
  components: {

  },

  data () {
    return {
      baseId: 0,
      dialogVisible: false,
      dialogCustom: false,
      farmsList: [],
      formCustom: {
        name: null,
        code: null
      },
      addForm: {
        landIds: null,
        agriCode: null,
        startTime: null,
        endTime: null,
        landName: null,
        dateTime: null,
        remark: '',
        userId: null
      },
      rules: {
        agriCode: [{ required: true, message: '请选择农事类型', trigger: 'blur' }],
        dateTime: [{ required: true, message: '请选择时间', trigger: 'blur' }],
        userId: [{ required: true, message: '请选择操作人', trigger: 'blur' }],
        landName: [{ required: true, message: '请选择地块', trigger: 'blur' }]
      },
      rulesCustom: {
        name: [{ required: true, message: '请输入类型名称', trigger: 'blur' }],
        code: [{ required: true, message: '请输入类型编码', trigger: 'blur' }]
      },
      userList: [], // 用户列表
      baseInfoList: [] // 地块列表
    }
  },
  computed: {
  },
  created () {
    this.baseId = this.$route.query.baseId
    this.addForm.landIds = this.$route.query.landId
    this.addForm.landName = this.$route.query.landName
    this.getData()
  },

  methods: {
    visibleChange (visible) {
      // 下拉框显示隐藏
      if (visible) {
        const ref = this.$refs.selectInput
        let popper = ref.$refs.popper
        if (popper.$el) popper = popper.$el
        // 判断是否有添加按钮
        if (!Array.from(popper.children).some(v => v.className === 'btn-box')) {
          const el = document.createElement('div')
          el.className = 'btn-box'
          el.innerHTML = `<a style="border-top:1px solid #CCCCCC;font-size:14px;padding: 0 20px;color: #606266;display:block;height: 34px;line-height: 34px;">
                            自定义
                          </a>`
          popper.appendChild(el)
          el.onclick = () => {
            this.dialogCustom = true
            this.$nextTick(() => {
              this.resetForm('ruleFormCustom')
            })
            // todo
          }
        }
      }
    },
    // 地块数据显示
    getAgriLand () {
      this.$refs.agriLand.getIdHas(this.addForm.landIds)
    },
    // 获取地块信息
    getLandIds (landIds, landName) {
      this.addForm.landName = landName.toString()
      this.$refs.ruleForm.validateField('landName')
      this.addForm.landIds = landIds
    },
    // 关闭
    dialogBeforeClose () {
      this.dialogVisible = false
      this.addForm = this.$options.data().addForm
    },
    // 关闭
    dialogBeforeCustom () {
      this.dialogCustom = false
      this.formCustom = this.$options.data().formCustom
    },
    // 地块列表
    getBaseInfolist () {
      getBaseInfolistApi().then(res => {
        this.baseInfoList = res.data
      })
    },
    getData () {
      // 农事类型
      this.getSysSonDictList('NS')
      this.getUserList()
      this.getBaseInfolist()
      this.getList()
    },
    //  获取计划信息
    getList () {
      if (!this.$route.query.planId) {
        return
      }
      getDetailById({ id: this.$route.query.planId }).then(res => {
        this.addForm = {
          ...res.data,
          landIds: this.$route.query.landId,
          dateTime: res.data.startTime && res.data.endTime ? [res.data.startTime, res.data.endTime] : []
        }
      })
    },
    // 字典接口
    async getSysSonDictList (code) {
      const res = await getSysSonDictListApi(code)
      this.farmsList = res.data
    },
    // 用户list
    async getUserList () {
      const res = await getUserListApi(this.baseId)
      // console.log(res)
      this.userList = res.data
    },
    // 返回
    back () {
      this.$router.go(-1)
    },
    addBtn () {
      this.dialogVisible = !this.dialogVisible
    },
    // 子组件事件--添加农资
    farmsStockData (data) {
      console.log(data, '选中的农资')
      this.addForm.name = data.name
      this.addForm.agriDicId = data.id
      this.addForm.specifications = data.specifications
      this.addForm.type = data.typeCode
      this.inputShow = true
      this.dialogVisible = false
    },
    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = this.$route.query.planId
            ? await updateAgriplan({
              baseId: this.baseId,
              id: this.addForm.id,
              landIds: this.addForm.landIds,
              agriCode: this.addForm.agriCode,
              startTime: this.addForm.dateTime[0],
              endTime: this.addForm.dateTime[1],
              remark: this.addForm.remark,
              userId: this.addForm.userId
            })
            : await addAgriplantApi({
              baseId: this.baseId,
              landIds: this.addForm.landIds,
              agriCode: this.addForm.agriCode,
              startTime: this.addForm.dateTime[0],
              endTime: this.addForm.dateTime[1],
              remark: this.addForm.remark,
              userId: this.addForm.userId
            })
          this.$message.success(res.msg ? res.msg : '提交成功')
          this.$router.go(-1)
        } else {
          // this.$message.error('请正确填写')
          return false
        }
      })
    },
    submitFormCustom (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = await addDic({
            code: this.formCustom.code,
            name: this.formCustom.name,
            isParent: 0,
            parentCode: 'NS',
            parentId: 3
          })
          this.$message.success(res.msg ? res.msg : '提交成功')
          this.getSysSonDictList('NS')
          this.dialogBeforeCustom()
        } else {
          // this.$message.error('请正确填写')
          return false
        }
      })
    },
    // 操作人下拉事件
    onSelectChange (value) {
      const userInfo = this.userList.filter((item) => item.userName === value)
      // console.log(userInfo)
      this.addForm.participantsId = userInfo[0].userId
    },
    // 农资弹窗关闭
    handleClose (dome) {
      dome()
    },
    // 重置表单
    resetForm (formName) {
      this.$refs[formName].clearValidate()
      this.$refs[formName].resetFields()
    },
    // 编辑
    editForm () {
      if (this.missionDetail.id !== null) {
        // console.log(this.missionDetail, '农事')
        this.addForm.code = this.missionDetail.code
        this.addForm.participants = this.missionDetail.participants
        // this.addForm.area = this.missionDetail.area
        this.addForm.time = this.missionDetail.time
        this.addForm.way = this.missionDetail.way
        if (this.missionDetail.picture !== undefined) {
          this.addForm.picture = this.missionDetail.picture.split(',')
            .map((picture) => picture)
        }
        this.addForm.remark = this.missionDetail.remark
      }
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .el-range-separator {
  color: #999
}
.back {
  position: absolute;
  top: 5%;
  left: 5%;
}
.name {
  display: inline-block;
  ::v-deep .el-form-item__content {
    display: flex;
  }
  .addBtn {
    margin-left: .5208vw;
  }
}
.selectInput {
  width: 280px;
}
.require {
  color: red;
}
::v-deep .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
  color: #00000000;
  margin-right: 0;
  display: none
}
.textRight {
  text-align: right
}
.noneClose {
  background-color: #ffffff;
  border-color: #cccccc;
  color: #999
}
</style>
<style>
/* .el-dialog__header {
  background: #002a52;
  text-align: center;
} */
.el-dialog__title {
  border-left: 3px solid #19b560;
  padding: 0 0.5208vw;
  font-weight: 500;
}
</style>
